package com.zhongfl.crm.lixiao.bean.resolve;

import com.heptagram.lixiao.bean.enums.OpportunityStage;
import com.heptagram.lixiao.bean.response.opportunity.LXOpportunityResponse;
import com.zhongfl.crm.enums.UserMatchStatus;
import com.zhongfl.crm.enums.boss.OrderSource;
import com.zhongfl.crm.enums.boss.OrderStatus;
import com.zhongfl.crm.lixiao.common.LxStatusConvertUtils;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.CustomerOrder;
import com.zhongfl.crm.model.boss.LxOrder;
import com.zhongfl.crm.model.boss.Order;
import com.zhongfl.crm.model.crm.StaffExt;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.crm.StaffExtService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import tech.heptagram.channel.api.model.Channel;
import tech.heptagram.channel.api.service.ChannelService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;

/**
 * @author wang.yuchuan
 * @date 2018/6/25
 */
@Component
public class OrderModelResolver implements ModelResolver<Order, LXOpportunityResponse.DataResult> {

    @Resource
    private LxUserService lxUserService;

    @Resource
    private ChannelService channelService;

    @Resource
    private StaffExtService staffExtService;

    public LxOrder resolveLXOrder(LXOpportunityResponse.DataResult obj) {
        LxOrder lxOrder = new LxOrder();
        lxOrder.setOrderType("opportunity");
        lxOrder.setCustomerId(obj.getCustomer().getId());
        lxOrder.setCustomerName(obj.getCustomer().getName());
        lxOrder.setLxId(obj.getId());
        lxOrder.setLxOrderAmount(new BigDecimal(obj.getExpectAmount()));
        lxOrder.setLxUserId(obj.getUser().getId());
        lxOrder.setTitle(obj.getTitle());
        lxOrder.setModifiedBy("System");
        lxOrder.setCreatedBy("System");
        return lxOrder;
    }

    @Override
    public Order resolve(LXOpportunityResponse.DataResult obj) throws ModelResolverException {

        Order order = new Order();
        order.setName(obj.getTitle());
        order.setSource(OrderSource.LI_XIAO);

        Channel channel = channelService.findByLxCustomerId(obj.getCustomer().getId());
        if (Objects.isNull(channel)) {
            throw new ModelResolverException("订单:" + obj.getTitle() + "没有找到id为" + obj.getCustomer().getId() + " ,名称为" + obj.getCustomer().getName() + " 的渠道");
        }
        order.setChannelName(channel.getChannelName());
        order.setChannelId(channel.getId());

        if (Objects.nonNull(obj.getExpectAmount())) {
            order.setLoanAmount(new BigDecimal(obj.getExpectAmount()).divide(new BigDecimal(10000), 2));
        }
        //修改一：添加贷款期限
        order.setLoanDuration(obj.getNumericAssetF59409().intValue());

        //修改二：添加总服务费率和渠道服务费率
        order.setTotalFeeRate(obj.getNumericAsset7de9b6());
        order.setChannelRate(obj.getNumericAsset86eeee());

        Long userId = obj.getUser().getId();
        LxUser lxUser = lxUserService.findByLxId(userId);
        if (Objects.isNull(lxUser)) {
            throw new ModelResolverException("lx用户id: " + userId + " 在销售表找不到");
        }
        if (lxUser.getMatchStatus().equals(UserMatchStatus.NO)) {
            throw new ModelResolverException("lx用户id: " + userId + " 名称:" + lxUser.getName() + " 还没有匹配到员工");
        }
        order.setBusinessManager(lxUser.getStaffName());
        order.setBusinessManagerStaffCode(lxUser.getStaffCode());
        order.setBusinessAssistantStaffCode(lxUser.getStaffCode());
        order.setBusinessAssistant(lxUser.getName());

        StaffExt ext = staffExtService.findByStaffCode(lxUser.getStaffCode());
        if (ObjectUtils.isEmpty(ext) || ObjectUtils.isEmpty(ext.getBusinessDeptId())) {
            throw new ModelResolverException("报单人姓名: " + lxUser.getStaffName() + " 没有匹配到报单部门");
        }
        order.setBusinessManagerAmibaId(ext.getBusinessDeptId());
        order.setBusinessManagerAmibaName(ext.getBusinessDeptName());

        order.setStatus(OrderStatus.STATUS_CREATED);
        order.setCreatedBy("System");

        return order;
    }

    /**
     * 从励销客户订单转为BOSS客户订单对象
     *
     * @param obj 励销客户订单对象
     * @return BOSS客户订单对象
     */
    public CustomerOrder resolve2CustomerOrder(LXOpportunityResponse.DataResult obj) throws ParseException {
        CustomerOrder customerOrder = new CustomerOrder();

        customerOrder.setLxCustomerOrderId(obj.getId());
        customerOrder.setCustomerName(obj.getTitle());

        Channel channel = channelService.findByLxCustomerId(obj.getCustomer().getId());
        if (Objects.isNull(channel)) {
            throw new ModelResolverException("订单:" + obj.getTitle() + "没有找到id为" + obj.getCustomer().getId() + " ,名称为" + obj.getCustomer().getName() + " 的渠道");
        }
        customerOrder.setChannelId(channel.getId());
        customerOrder.setChannelName(channel.getChannelName());

        if (StringUtils.isNotEmpty(obj.getExpectAmount())) {
            customerOrder.setLoanAmount(new BigDecimal(obj.getExpectAmount()));
        }

        if (Objects.nonNull(obj.getNumericAssetF59409())) {
            customerOrder.setLoanDuration(obj.getNumericAssetF59409().intValue());
        }

        if (Objects.nonNull(obj.getNumericAsset7de9b6())) {
            customerOrder.setTotalFeeRate(obj.getNumericAsset7de9b6());
        }

        if (Objects.nonNull(obj.getNumericAsset86eeee())) {
            customerOrder.setChannelFeeRate(obj.getNumericAsset86eeee());
        }

        if (Objects.nonNull(obj.getGetTime())) {
            Date date = DateUtils.parseDate(obj.getGetTime(), "yyyy-MM-dd");
            customerOrder.setInterviewDate(date);
        }

        OpportunityStage opportunityStage = OpportunityStage.valueOf(Long.valueOf(obj.getStage()));
        OrderStatus orderStatus = LxStatusConvertUtils.convertLxStatus2BossOrderStatus(opportunityStage.name());
        if (Objects.isNull(orderStatus)) {
            throw new ModelResolverException("订单:" + obj.getTitle() + "状态未找到");
        }
        customerOrder.setCustomerOrderStatus(orderStatus.name());

        LxUser lxUser = lxUserService.findByLxId(obj.getUser().getId());
        if (Objects.isNull(lxUser)) {
            throw new ModelResolverException("lx用户id: " + obj.getUser().getId() + " 在销售表找不到");
        }
        if (lxUser.getMatchStatus().equals(UserMatchStatus.NO)) {
            throw new ModelResolverException("lx用户id: " + obj.getUser().getId() + " 名称:" + lxUser.getName() + " 还没有匹配到员工");
        }

        customerOrder.setBusinessManagerStaffCode(lxUser.getStaffCode());
        customerOrder.setBusinessManagerStaffName(lxUser.getStaffName());

        customerOrder.setBusinessAssistantStaffCode(lxUser.getStaffCode());
        customerOrder.setBusinessAssistantStaffName(lxUser.getStaffName());

        StaffExt ext = staffExtService.findByStaffCode(lxUser.getStaffCode());
        if (ObjectUtils.isEmpty(ext) || ObjectUtils.isEmpty(ext.getBusinessDeptId())) {
            throw new ModelResolverException("报单人姓名: " + lxUser.getStaffName() + " 没有匹配到名称为: " + lxUser.getDepartmentName() + " 的报单部门");
        }
        customerOrder.setBusinessManagerAmibaId(ext.getBusinessDeptId());
        customerOrder.setBusinessManagerAmibaName(ext.getBusinessDeptName());

        customerOrder.setCreatedBy(obj.getCreator().getName());
        customerOrder.setCreatedAt(DateUtils.parseDate(obj.getCreatedAt(), "yyyy-MM-dd HH:mm"));
        customerOrder.setUpdatedBy(obj.getCreator().getName());
        customerOrder.setUpdatedAt(DateUtils.parseDate(obj.getUpdatedAt(), "yyyy-MM-dd HH:mm"));

        return customerOrder;
    }
}
